//
//  GroupAddUserVC.swift
//  YueChat
//
//  Created by IMac on 2024/10/9.
//

import UIKit

class GroupAddUserVC: BaseVC {
    var info =  DMCCGroup()
        
    var allDataArray : [String: Any]?
//    var indexArray : Array<Any> = []
    // 排序后分组数据
    private var objectsArray : [[Any]]?
    // 头部标题keys
    private var keysArray:[String]? = []

    var confirmBlock: (([String]) -> Void)?


    

    init (group:DMCCGroup) {
        super.init(nibName: nil, bundle: nil)
        self.info = group
    }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        override func viewDidLoad() {
            super.viewDidLoad()

            
            self.title = "邀请联系人"
            tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
            navigationController?.navigationBar.topItem?.title = KLocalizedString("ChatSelectFriend")

            
//            let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(userFresh))
//            header.lastUpdatedTimeLabel!.isHidden = true
//            header.stateLabel!.isHidden = true
//            tableView.mj_header = header

            getData()

            navigationItem.rightBarButtonItem = UIBarButtonItem(customView: setBtn)
            
        }

        @objc func userFresh() {
            dataSource.removeAll()
            getData()
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.tableView.mj_header!.endRefreshing()
            }
        }

    lazy var setBtn : UIButton = {
            let button = UIButton(frame: .zero)
            button.setTitle(KLocalizedString("Sure"), for: .normal)
            button.setTitleColor(UIColor.black, for: .normal)
            button.addTarget(self, action: #selector(setBtnClick), for: .touchUpInside)
            return button
        }()

        @objc func setBtnClick() {
//            let array = indexDataSource.compactMap { 
//                allDataSource[$0]?.filter { !$0.isNotSelect && $0.isSelect
//                }.map { $0.userId } } as! [String]
            var selectedUserIds: [String] = []

            objectsArray?.compactMap({ arr in
                for model in arr {
                    let user = model as! DMCCUser
                    if !user.isNotSelect && user.isSelect {
                        selectedUserIds.append(user.userId)
                    }
                }
            })
            
            confirmBlock?(selectedUserIds)
            navigationController?.popViewController(animated: true)
        }

    override func getData() {
            dataSource.removeAll()
        let friendArray = gosnFriend.getFriendList()//DMCCIMService.getInstance().getFriendList(false)
        for info in friendArray {
            getUserInfo(friendId: info.friendId, arrayCount: friendArray.count)
        }
        
//        friendArray.foEach { getUserInfo(friendId: $0.userId, arrayCount: friendArray.count) }
        }

        func getUserInfo(friendId: String, arrayCount: Int) {
            let user = gosnUser.getUserInfoDefault(friendId)
            dataSource.append(user as DMCCUser)
            if dataSource.count == arrayCount {
                sortData()
            }
        }

        func sortData() {
            
            DispatchQueue.global().async {
    //            allDataArray =
                UILocalizedIndexedCollation.getCurrentKeysAndObjectsData(needSortArray: (self.dataSource as NSArray) as! [DMCCUser] as NSArray) { (dataArray,titleArray) in
                    self.objectsArray =  dataArray
                    self.keysArray    = titleArray
                    self.filterData()
                }
            }
            
//            allDataSource = HCSortString.sortAndGroup(forArray: dataSource, propertyName: "alias")
//            indexDataSource = HCSortString.sortForStringArray(allDataSource.keys)
//            DispatchQueue.main.async { [self] in
//                filterData()
//            }
        }

        func filterData() {
            let memberList = gosnMember.getMemberList(info.groupId, 0, 1000)//DMCCIMService.getInstance().getGroupAllMember(info.groupId)
            memberList.forEach { member in
                let user = gosnUser.getUserInfoDefault(member.memberId)
                
                objectsArray?.compactMap({ arr in
                    for model in arr {
                        let userT = model as? DMCCUser
                        if user.userId == userT!.userId {
                            userT!.isSelect = true
                            userT!.isNotSelect = true
                            break
                        }
                    }
                })
                
//                if let index = indexDataSource.firstIndex(of: user!.alias.prefix(1).uppercased()) {
//                    if let userN = allDataSource[indexDataSource[index]]!.first(where: { $0.userId == user!.userId }) {
//                        userN.isSelect = true
//                        userN.isNotSelect = true
//                    }
//                }
            }
            GK_main_async_safe {
                self.tableView.reloadData()
            }
        }

        func numberOfSections(in tableView: UITableView) -> Int {
            return keysArray!.count
        }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = objectsArray![section] as Array<Any>
        return array.count
        }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//            let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell" for: indexPath) as! UserCell
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        cell.selectImg.isHidden = false
        let array = objectsArray![indexPath.section]
        let user = array[indexPath.row] as! DMCCUser
            cell.icon.sd_setImage(with: URL(string: user.portrait), placeholderImage: SDImageDefault)
            cell.nickName.text = user.getAlias()
            if user.isNotSelect {
                cell.backgroundColor = kGrayBG
                cell.selectImg.image = UIImage(named: "select_s")
            } else {
                cell.backgroundColor = UIColor.white
                cell.selectImg.image = user.isSelect ? UIImage(named: "select_s") : UIImage(named: "select_n")
            }
            return cell
        }

        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            tableView.deselectRow(at: indexPath, animated: true)
            let array = objectsArray![indexPath.section]
            let user = array[indexPath.row] as! DMCCUser
            
            if !user.isNotSelect {
                user.isSelect = !user.isSelect
            }
            tableView.reloadData()
        }

        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            if section != 0 {
                return keysArray?[section - 1]
            }
            return ""
        }

        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
            if section != 0 {
                return 10.0
            }
            return 0.001
        }

        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            return 0
        }

        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 60
        }


}
